using System;
using System.Collections;
using System.Xml;
using MSScriptControl;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.ManagedCode;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	/// <summary>
	/// Summary description for ScriptCodeOnMergeRequestWorker.
	/// </summary>
	class ScriptCodeOnMergeRequestWorker
	{
		
		public static void OnMergeRequest(Form form,ArrayList xmlList)
		{
			ScriptSource scriptSource = form.Manifest.ScriptSource;
			if( scriptSource == null )
			{
				return;
			}

			try
			{
				if( form.ScriptControlContext == null )
				{
					ScriptControlContext.buildContext( scriptSource, form );
				}

				XDocument xdoc = form.ScriptControlContext.XDocument;
				Application app = form.ScriptControlContext.Application;

				ScriptControl scriptControl = form.ScriptControlContext.ScriptControl;
				
				foreach( Procedure proc in scriptControl.Procedures )
				{
					if( proc.Name.Equals( "XDocument_OnMergeRequest" ) )
					{
						int index = 0;
						foreach(string mergeXml in xmlList)
						{
							XmlDocument xmlDoc = new XmlDocument();
							xmlDoc.LoadXml( mergeXml );
							NamespaceResolver nsResolver = new NamespaceResolver(xmlDoc);

							XMLDocument xDoc = new XMLDocument(form, xmlDoc, nsResolver);

							MergeEvent mergeEvent = new MergeEvent( xdoc, xDoc );
							mergeEvent.Count = xmlList.Count;
							mergeEvent.Index = index;

							object[] param = new object[]{ mergeEvent };
							scriptControl.Run( "XDocument_OnMergeRequest", ref param );

							index ++;
						}
					}
				}
			}
			catch( Exception e )
			{
                FormUtil.addInnerExceptionMassage(form, "XDocument_OnMergeRequest", e);
			}
		}

	}
}
